#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>
#include "LockGuard.hpp"

using namespace std;
const int capatity = 5;
template <class T>
class BlockQueue
{
public:
    BlockQueue(int cap = capatity) : _capacity(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
    }
    bool ISfull()
    {
        return _q.size() == _capacity;
    }
    bool IStemp()
    {
        return _q.size() == 0;
    }
    void push(const T &in) // 生产者
    {
        LockGuard guard(&_mutex);
        while (ISfull())
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
            _q.push(in);
            pthread_cond_signal(&_c_cond);
    }
    void pop(T *out) // 消费者
    {
        LockGuard guard(&_mutex);
        while (IStemp())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }

            *out = _q.front();
            _q.pop();
            pthread_cond_signal(&_p_cond);

    }
    ~BlockQueue()
    {
        // pthread_mutex_destory(&_mutex);
        // pthread_cond_destory(&_p_cond);
        // pthread_cond_destory(&_c_cond);
         pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);
    }

private:
    queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond; // 给生产者的
    pthread_cond_t _c_cond; //  给消费者的
};